// filepath: [PreGeneratedStoryController.java](http://_vscodecontentref_/2)
package com.javaee.wordtree.controller;

import com.javaee.wordtree.entity.*;
import com.javaee.wordtree.mapper.*;
import com.javaee.wordtree.service.MemoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value; // 添加这个导入
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/api/story")
@Slf4j
public class PreGeneratedStoryController {

    private String cleanContent(String content) {
        if (content == null)
            return "";
        // 移除所有 <think></think> 标签及其内容
        return content.replaceAll("<think>[\\s\\S]*?</think>", "").trim();
    }

    @Resource
    private StoryTemplateMapper storyTemplateMapper;

    @Resource
    private StoryPageMapper storyPageMapper;

    @Resource
    private UserStoryProgressMapper userStoryProgressMapper;

    @Resource
    private MemoryService memoryService;

    // 添加图像生成相关依赖
    @Value("${image.generation.url:http://localhost:8081/generate}")
    private String imageGenerationUrl;

    @Resource
    private RestTemplate restTemplate;

    // 添加图像生成方法（复制自DeepseekController）
    private String generateSceneImage(String storyText) {
        try {
            // 1. 提取故事中适合生成图像的描述
            String imagePrompt = extractImagePrompt(storyText);

            // 2. 调用图像生成服务
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            Map<String, Object> requestBody = new ConcurrentHashMap<>();
            requestBody.put("prompts", List.of(imagePrompt));
            requestBody.put("num_inference_steps", 30);
            requestBody.put("guidance_scale", 7.5);

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);

            log.info("正在生成场景图像，提示词: {}", imagePrompt);
            ResponseEntity<Map> response = restTemplate.postForEntity(
                    imageGenerationUrl,
                    request,
                    Map.class);

            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                @SuppressWarnings("unchecked")
                List<String> images = (List<String>) response.getBody().get("generated_images");
                if (images != null && !images.isEmpty()) {
                    log.info("场景图像生成成功");
                    return images.get(0);
                }
            }

            log.error("图像生成服务返回异常: {}", response);
            return null;
        } catch (Exception e) {
            log.error("调用图像生成服务失败", e);
            return null;
        }
    }

    // 添加图像提示词提取方法
    private String extractImagePrompt(String storyText) {
        // 如果提取失败，使用故事的前100个字符加上风格描述
        String fallbackPrompt = storyText;
        if (fallbackPrompt.length() > 100) {
            fallbackPrompt = fallbackPrompt.substring(0, 100);
        }
        return fallbackPrompt
                + ", 8-bit, simple, colorful, single scene, cute, clear composition, centered subject, clean background";
    }

    /**
     * 获取预生成的故事
     */
    /**
     * 获取预生成的故事
     */
    @PostMapping("/pregenerated")
    public ResponseEntity<Map<String, Object>> getPreGeneratedStory(@RequestParam String userID) {
        log.info("=== 开始获取预生成故事 ===");
        log.info("用户ID: {}", userID);

        try {
            // 1. 获取用户学习的单词列表
            log.info("步骤1: 获取用户学习单词");
            List<String> wordList = getUserKeywords(userID);
            log.info("用户关键词数量: {}", wordList.size());

            // 2. 检查数据库中是否有故事模板
            log.info("步骤2: 检查数据库中的故事模板");
            List<StoryTemplate> allTemplates = storyTemplateMapper.selectList(null);
            log.info("数据库中总共有 {} 个故事模板", allTemplates != null ? allTemplates.size() : 0);

            if (allTemplates == null || allTemplates.isEmpty()) {
                log.warn("数据库中没有故事模板，尝试创建测试数据");
                createTestData();
                allTemplates = storyTemplateMapper.selectList(null);
                log.info("创建测试数据后，模板数量: {}", allTemplates != null ? allTemplates.size() : 0);
            }

            StoryTemplate template = findBestTemplate(wordList);
            if (template == null) {
                log.error("没有找到合适的故事模板");
                return ResponseEntity.badRequest()
                        .body(Map.of("error", "没有找到合适的故事模板，正在为您生成中，请稍后重试",
                                "debug", "数据库中模板数量: " + (allTemplates != null ? allTemplates.size() : 0)));
            }

            // 3. 获取用户进度或创建新进度
            log.info("步骤3: 获取用户故事进度");
            UserStoryProgress progress = getUserProgress(userID, template.getId());
            log.info("用户进度: 当前页面ID={}", progress.getCurrentPageId());

            // 4. 获取当前应该显示的故事页面
            log.info("步骤4: 获取当前故事页面");
            StoryPage currentPage = getCurrentPage(progress);
            log.info("当前页面: {}",
                    currentPage != null ? "ID=" + currentPage.getId() + ", 页码=" + currentPage.getPageNumber() : "null");

            if (currentPage == null) {
                log.error("无法获取当前故事页面");
                return ResponseEntity.badRequest()
                        .body(Map.of("error", "故事页面数据异常",
                                "debug", "模板ID=" + template.getId() + ", 进度页面ID=" + progress.getCurrentPageId()));
            }

            // 5. 重建完整的页面历史
            log.info("步骤5: 重建页面历史");
            List<StoryPage> pageHistory = rebuildPageHistory(progress, template.getId());
            log.info("重建的页面历史数量: {}", pageHistory.size());

            // 6. 构建返回结果
            log.info("步骤6: 构建返回结果");
            Map<String, Object> result = new HashMap<>();
            result.put("template", template);
            result.put("currentPage", currentPage);
            result.put("pageHistory", pageHistory); // 新增：返回完整页面历史
            result.put("currentPageIndex", pageHistory.size() - 1); // 新增：当前页面在历史中的索引
            result.put("progress", progress);
            result.put("keywords", wordList);

            log.info("=== 成功获取预生成故事 ===");
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("=== 获取预生成故事失败 ===", e);
            return ResponseEntity.badRequest()
                    .body(Map.of("error", "获取故事失败: " + e.getMessage(),
                            "debug", e.getClass().getSimpleName()));
        }
    }

    /**
     * 重建用户的页面历史
     */
    private List<StoryPage> rebuildPageHistory(UserStoryProgress progress, Long templateId) {
        List<StoryPage> pageHistory = new ArrayList<>();

        try {
            // 获取选择历史
            List<Integer> choicesMade = progress.getChoicesMade();
            if (choicesMade == null || choicesMade.isEmpty()) {
                // 如果没有选择历史，只返回第一页
                StoryPage firstPage = storyPageMapper.selectOne(
                        new LambdaQueryWrapper<StoryPage>()
                                .eq(StoryPage::getTemplateId, templateId)
                                .isNull(StoryPage::getParentPageId)
                                .orderByAsc(StoryPage::getPageNumber)
                                .last("LIMIT 1"));
                if (firstPage != null) {
                    firstPage.setEnglishContent(cleanContent(firstPage.getEnglishContent()));
                    firstPage.setChineseContent(cleanContent(firstPage.getChineseContent()));
                    pageHistory.add(firstPage);
                }
                return pageHistory;
            }

            // 根据选择历史重建页面路径
            StoryPage currentPage = storyPageMapper.selectOne(
                    new LambdaQueryWrapper<StoryPage>()
                            .eq(StoryPage::getTemplateId, templateId)
                            .isNull(StoryPage::getParentPageId)
                            .orderByAsc(StoryPage::getPageNumber)
                            .last("LIMIT 1"));

            if (currentPage == null) {
                log.error("找不到模板 {} 的第一页", templateId);
                return pageHistory;
            }

            // 添加第一页
            currentPage.setEnglishContent(cleanContent(currentPage.getEnglishContent()));
            currentPage.setChineseContent(cleanContent(currentPage.getChineseContent()));
            pageHistory.add(currentPage);

            // 根据选择历史依次查找后续页面
            Long parentPageId = currentPage.getId();
            for (int i = 0; i < choicesMade.size(); i++) {
                Integer choiceIndex = choicesMade.get(i);

                // 查找下一页
                StoryPage nextPage = storyPageMapper.selectOne(
                        new LambdaQueryWrapper<StoryPage>()
                                .eq(StoryPage::getParentPageId, parentPageId)
                                .eq(StoryPage::getChoiceIndex, choiceIndex));

                if (nextPage != null) {
                    nextPage.setEnglishContent(cleanContent(nextPage.getEnglishContent()));
                    nextPage.setChineseContent(cleanContent(nextPage.getChineseContent()));
                    pageHistory.add(nextPage);
                    parentPageId = nextPage.getId();
                } else {
                    log.warn("选择历史中第 {} 个选择 {} 找不到对应页面，可能是动态结局", i, choiceIndex);
                    // 创建动态结局页面
                    StoryPage endingPage = createDynamicEnding(choiceIndex, templateId, parentPageId);
                    pageHistory.add(endingPage);
                    break;
                }
            }

            log.info("成功重建页面历史，共 {} 页", pageHistory.size());
            return pageHistory;

        } catch (Exception e) {
            log.error("重建页面历史失败", e);
            return pageHistory;
        }
    }

    /**
     * 创建测试数据
     */
    private void createTestData() {
        log.info("开始创建测试数据");

        try {
            // 创建故事模板
            StoryTemplate template = new StoryTemplate();
            template.setTitle("神秘森林的冒险");
            template.setDescription("一个关于勇敢探险者在神秘森林中冒险的故事");
            template.setDifficultyLevel("beginner");
            template.setWordList(Arrays.asList("adventure", "forest", "journey", "mystery", "brave"));
            template.setTheme("adventure");
            template.setTotalPages(1);

            storyTemplateMapper.insert(template);
            log.info("创建故事模板成功，ID: {}", template.getId());

            // 创建第一页
            StoryPage firstPage = new StoryPage();
            firstPage.setTemplateId(template.getId());
            firstPage.setPageNumber(1);
            firstPage.setParentPageId(null);
            firstPage.setChoiceIndex(null);
            firstPage.setEnglishContent(
                    "Welcome to the Mysterious Forest! You are a brave *adventurer* standing at the edge of an ancient forest. The trees whisper secrets in the wind, and mysterious paths lead deeper into the unknown. What will you choose to do?");
            firstPage.setChineseContent("欢迎来到神秘森林！你是一位勇敢的冒险者，站在一片古老森林的边缘。树木在风中低语着秘密，神秘的小径通向未知的深处。你会选择做什么？");
            firstPage.setChoices(Arrays.asList("进入森林探险", "寻找当地向导", "搭建营地休息"));
            firstPage.setIsEnding(false);

            storyPageMapper.insert(firstPage);
            log.info("创建第一页成功，ID: {}", firstPage.getId());

            // 创建分支页面
            StoryPage page2 = new StoryPage();
            page2.setTemplateId(template.getId());
            page2.setPageNumber(2);
            page2.setParentPageId(firstPage.getId());
            page2.setChoiceIndex(0);
            page2.setEnglishContent(
                    "You bravely enter the forest. The *adventure* begins! Ancient trees tower above you, and you *discover* a hidden treasure chest. Your *journey* continues...");
            page2.setChineseContent("你勇敢地进入了森林。冒险开始了！古老的大树高耸在你头顶，你发现了一个隐藏的宝藏箱。你的冒险继续进行...");
            page2.setChoices(Arrays.asList("打开宝藏箱", "继续探索"));
            page2.setIsEnding(true);

            storyPageMapper.insert(page2);
            log.info("创建分支页面成功，ID: {}", page2.getId());

            // 更新模板页数
            template.setTotalPages(2);
            storyTemplateMapper.updateById(template);

            log.info("测试数据创建完成");

        } catch (Exception e) {
            log.error("创建测试数据失败", e);
        }
    }

    private StoryTemplate findBestTemplate(List<String> wordList) {
        log.info("开始查找最佳故事模板");

        try {
            // 1. 首先返回任意模板
            List<StoryTemplate> allTemplates = storyTemplateMapper.selectList(null);
            if (allTemplates != null && !allTemplates.isEmpty()) {
                StoryTemplate selected = allTemplates.get(0);
                log.info("选择模板: {}", selected.getTitle());
                return selected;
            }

            log.warn("数据库中没有任何故事模板");
            return null;

        } catch (Exception e) {
            log.error("查找最佳模板时发生异常", e);
            return null;
        }
    }

    private UserStoryProgress getUserProgress(String userId, Long templateId) {
        log.info("获取用户故事进度: 用户ID={}, 模板ID={}", userId, templateId);

        try {
            // 首先尝试从数据库获取已有的未完成进度
            UserStoryProgress progress = userStoryProgressMapper.selectOne(
                    new LambdaQueryWrapper<UserStoryProgress>()
                            .eq(UserStoryProgress::getUserId, userId)
                            .eq(UserStoryProgress::getTemplateId, templateId)
                            .eq(UserStoryProgress::getIsCompleted, false)
                            .orderByDesc(UserStoryProgress::getUpdatedAt)
                            .last("LIMIT 1"));

            if (progress != null) {
                log.info("找到已有的未完成进度: 当前页面ID={}", progress.getCurrentPageId());

                // 验证当前页面是否为结局页面
                StoryPage currentPage = storyPageMapper.selectById(progress.getCurrentPageId());
                if (currentPage != null && currentPage.getIsEnding()) {
                    log.info("当前进度指向结局页面，自动标记为完成并创建新进度");
                    // 标记这个进度为完成
                    progress.setIsCompleted(true);
                    progress.setCompletedAt(LocalDateTime.now());
                    userStoryProgressMapper.updateById(progress);
                    // 继续创建新进度
                } else if (currentPage != null) {
                    // 当前页面有效且不是结局，返回这个进度
                    return progress;
                } else {
                    log.warn("当前进度指向的页面不存在，创建新进度");
                }
            }

            // 没有找到有效的未完成进度，创建新进度
            log.info("创建新的用户进度记录");

            // 获取第一个页面
            StoryPage firstPage = storyPageMapper.selectOne(
                    new LambdaQueryWrapper<StoryPage>()
                            .eq(StoryPage::getTemplateId, templateId)
                            .isNull(StoryPage::getParentPageId)
                            .orderByAsc(StoryPage::getPageNumber)
                            .last("LIMIT 1"));

            if (firstPage == null) {
                log.error("模板 {} 没有找到第一页", templateId);
                throw new RuntimeException("故事模板缺少第一页");
            }
            log.info("找到第一页: ID={}, 页码={}", firstPage.getId(), firstPage.getPageNumber());

            // 创建新的进度记录
            progress = new UserStoryProgress();
            progress.setUserId(userId);
            progress.setTemplateId(templateId);
            progress.setCurrentPageId(firstPage.getId());
            progress.setChoicesMade(new ArrayList<>());
            progress.setIsCompleted(false);
            progress.setStartedAt(LocalDateTime.now());
            progress.setUpdatedAt(LocalDateTime.now());

            // 保存到数据库
            try {
                userStoryProgressMapper.insert(progress);
                log.info("新进度记录已保存到数据库，ID={}", progress.getId());
            } catch (Exception e) {
                log.warn("保存进度到数据库失败，使用内存进度: {}", e.getMessage());
            }

            return progress;

        } catch (Exception e) {
            log.error("获取用户进度时发生异常", e);
            throw new RuntimeException("获取用户进度失败", e);
        }
    }

    private StoryPage getCurrentPage(UserStoryProgress progress) {
        log.info("获取当前故事页面: 页面ID={}", progress.getCurrentPageId());

        try {
            StoryPage page = storyPageMapper.selectById(progress.getCurrentPageId());
            if (page == null) {
                log.error("找不到页面ID为 {} 的故事页面", progress.getCurrentPageId());
            } else {
                log.info("成功获取故事页面: 页码={}", page.getPageNumber());

                // 清理内容
                page.setEnglishContent(cleanContent(page.getEnglishContent()));
                page.setChineseContent(cleanContent(page.getChineseContent()));

                // 生成场景图片（如果还没有）
                if (page.getSceneImageBase64() == null || page.getSceneImageBase64().isEmpty()) {
                    log.info("为页面 {} 生成场景图片", page.getId());
                    String sceneImage = generateSceneImage(page.getEnglishContent());
                    if (sceneImage != null) {
                        page.setSceneImageBase64(sceneImage);
                        // 更新数据库
                        try {
                            storyPageMapper.updateById(page);
                            log.info("页面 {} 的场景图片已保存到数据库", page.getId());
                        } catch (Exception e) {
                            log.warn("保存场景图片到数据库失败: {}", e.getMessage());
                        }
                    } else {
                        log.warn("页面 {} 的场景图片生成失败", page.getId());
                    }
                }
            }
            return page;

        } catch (Exception e) {
            log.error("获取当前页面时发生异常", e);
            throw new RuntimeException("获取当前页面失败", e);
        }
    }

    /**
     * 处理用户选择，获取下一个页面
     */
    @PostMapping("/choice")
    public ResponseEntity<Map<String, Object>> processChoice(
            @RequestParam String userID,
            @RequestParam Long templateId,
            @RequestParam Long currentPageId,
            @RequestParam Integer choiceIndex) {

        try {
            log.info("处理用户选择: 用户={}, 模板={}, 当前页面={}, 选择={}",
                    userID, templateId, currentPageId, choiceIndex);

            // 1. 获取当前用户进度
            UserStoryProgress progress = getUserProgress(userID, templateId);

            // 2. 查找下一个页面
            StoryPage nextPage = storyPageMapper.selectOne(
                    new LambdaQueryWrapper<StoryPage>()
                            .eq(StoryPage::getParentPageId, currentPageId)
                            .eq(StoryPage::getChoiceIndex, choiceIndex));

            Map<String, Object> result = new HashMap<>();

            if (nextPage != null) {
                log.info("找到下一页: ID={}, 页码={}", nextPage.getId(), nextPage.getPageNumber());

                // 更新用户进度
                updateUserProgress(progress, nextPage.getId(), choiceIndex);

                // 清理内容
                nextPage.setEnglishContent(cleanContent(nextPage.getEnglishContent()));
                nextPage.setChineseContent(cleanContent(nextPage.getChineseContent()));

                // 生成场景图片（如果还没有）
                if (nextPage.getSceneImageBase64() == null || nextPage.getSceneImageBase64().isEmpty()) {
                    log.info("为下一页 {} 生成场景图片", nextPage.getId());
                    String sceneImage = generateSceneImage(nextPage.getEnglishContent());
                    if (sceneImage != null) {
                        nextPage.setSceneImageBase64(sceneImage);
                        // 更新数据库
                        try {
                            storyPageMapper.updateById(nextPage);
                            log.info("下一页 {} 的场景图片已保存到数据库", nextPage.getId());
                        } catch (Exception e) {
                            log.warn("保存场景图片到数据库失败: {}", e.getMessage());
                        }
                    }
                }

                // 获取关键词列表
                List<String> wordList = getUserKeywords(userID);

                result.put("success", true);
                result.put("page", nextPage);
                result.put("isEnding", nextPage.getIsEnding());
                result.put("message", nextPage.getIsEnding() ? "恭喜您完成了这个冒险故事！" : "继续您的冒险！");
                result.put("currentPageId", nextPage.getId());
                result.put("keywords", wordList);
                result.put("progress", progress); // 返回更新后的进度

            } else {
                // 没有找到下一页，创建一个动态结局
                log.info("没有找到下一页，创建动态结局");

                StoryPage endingPage = createDynamicEnding(choiceIndex, templateId, currentPageId);

                // 标记故事完成
                updateUserProgress(progress, endingPage.getId(), choiceIndex);
                progress.setIsCompleted(true);
                progress.setCompletedAt(LocalDateTime.now());
                saveUserProgress(progress);

                result.put("success", true);
                result.put("page", endingPage);
                result.put("isEnding", true);
                result.put("message", "恭喜您完成了这个冒险故事！");
                result.put("currentPageId", endingPage.getId());
                result.put("keywords", getUserKeywords(userID));
                result.put("progress", progress);
            }

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("处理用户选择失败", e);
            return ResponseEntity.badRequest()
                    .body(Map.of("error", "处理选择失败，请重试",
                            "debug", e.getMessage()));
        }
    }

    /**
     * 更新用户进度
     */
    private void updateUserProgress(UserStoryProgress progress, Long newPageId, Integer choiceIndex) {
        // 更新当前页面ID
        progress.setCurrentPageId(newPageId);

        // 添加选择到历史记录
        List<Integer> choices = progress.getChoicesMade();
        if (choices == null) {
            choices = new ArrayList<>();
        }
        choices.add(choiceIndex);
        progress.setChoicesMade(choices);

        // 更新时间戳
        progress.setUpdatedAt(LocalDateTime.now());

        // 保存到数据库
        saveUserProgress(progress);

        log.info("用户进度已更新: 页面ID={}, 选择历史={}", newPageId, choices);
    }

    /**
     * 保存用户进度到数据库
     */
    private void saveUserProgress(UserStoryProgress progress) {
        try {
            if (progress.getId() != null) {
                // 更新已有记录
                userStoryProgressMapper.updateById(progress);
                log.debug("用户进度已更新到数据库");
            } else {
                // 插入新记录
                userStoryProgressMapper.insert(progress);
                log.debug("用户进度已插入到数据库");
            }
        } catch (Exception e) {
            log.warn("保存用户进度到数据库失败: {}", e.getMessage());
        }
    }

    /**
     * 获取用户关键词列表
     */
    private List<String> getUserKeywords(String userID) {
        try {
            List<String> wordList = memoryService.getTodayLearnedWords(userID).stream()
                    .map(Word::getWord)
                    .collect(Collectors.toList());

            if (!wordList.isEmpty()) {
                return wordList;
            }
        } catch (Exception e) {
            log.warn("获取用户学习单词失败: {}", e.getMessage());
        }

        // 返回默认单词列表
        return Arrays.asList("adventure", "journey", "discover", "mystery", "explore");
    }

    /**
     * 创建动态结局页面
     */
    private StoryPage createDynamicEnding(Integer choiceIndex, Long templateId, Long currentPageId) {
        // 根据选择创建不同的结局
        String[] endings = {
                "您选择了勇敢前进，最终发现了传说中的宝藏！冒险成功结束。",
                "您的谨慎选择让您安全地完成了这次冒险，获得了宝贵的经验。",
                "您的智慧选择开启了一条全新的道路，故事还将继续..."
        };

        String[] englishEndings = {
                "You chose to move forward bravely and finally discovered the legendary treasure! The adventure ends successfully.",
                "Your cautious choice allows you to safely complete this adventure and gain valuable experience.",
                "Your wise choice opens up a new path, and the story continues..."
        };

        String ending = choiceIndex < endings.length ? endings[choiceIndex] : "您的选择让故事有了独特的结局！";
        String englishEnding = choiceIndex < englishEndings.length ? englishEndings[choiceIndex]
                : "Your choice has led to a unique ending!";

        // 创建结局页面对象
        StoryPage endingPage = new StoryPage();
        endingPage.setId(currentPageId + 1000); // 临时ID
        endingPage.setTemplateId(templateId);
        endingPage.setPageNumber(99);
        endingPage.setEnglishContent(englishEnding);
        endingPage.setChineseContent(ending);
        endingPage.setChoices(Arrays.asList("重新开始冒险", "查看故事总结"));
        endingPage.setIsEnding(true);

        // 为结局页面生成图片
        String sceneImage = generateSceneImage(englishEnding);
        if (sceneImage != null) {
            endingPage.setSceneImageBase64(sceneImage);
        }

        return endingPage;
    }

    /**
     * 重新开始故事
     */
    @PostMapping("/restart")
    public ResponseEntity<Map<String, Object>> restartStory(
            @RequestParam String userID,
            @RequestParam Long templateId) {

        try {
            log.info("重新开始故事: 用户={}, 模板={}", userID, templateId);

            // 1. 标记当前进度为完成（如果存在）
            UserStoryProgress existingProgress = userStoryProgressMapper.selectOne(
                    new LambdaQueryWrapper<UserStoryProgress>()
                            .eq(UserStoryProgress::getUserId, userID)
                            .eq(UserStoryProgress::getTemplateId, templateId)
                            .eq(UserStoryProgress::getIsCompleted, false));

            if (existingProgress != null) {
                existingProgress.setIsCompleted(true);
                existingProgress.setCompletedAt(LocalDateTime.now());
                userStoryProgressMapper.updateById(existingProgress);
            }

            // 2. 创建新的进度记录
            StoryPage firstPage = storyPageMapper.selectOne(
                    new LambdaQueryWrapper<StoryPage>()
                            .eq(StoryPage::getTemplateId, templateId)
                            .isNull(StoryPage::getParentPageId)
                            .orderByAsc(StoryPage::getPageNumber)
                            .last("LIMIT 1"));

            if (firstPage == null) {
                return ResponseEntity.badRequest()
                        .body(Map.of("error", "故事模板数据异常"));
            }

            UserStoryProgress newProgress = new UserStoryProgress();
            newProgress.setUserId(userID);
            newProgress.setTemplateId(templateId);
            newProgress.setCurrentPageId(firstPage.getId());
            newProgress.setChoicesMade(new ArrayList<>());
            newProgress.setIsCompleted(false);
            newProgress.setStartedAt(LocalDateTime.now());
            newProgress.setUpdatedAt(LocalDateTime.now());

            userStoryProgressMapper.insert(newProgress);

            // 3. 返回第一页
            firstPage.setEnglishContent(cleanContent(firstPage.getEnglishContent()));
            firstPage.setChineseContent(cleanContent(firstPage.getChineseContent()));

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("page", firstPage);
            result.put("progress", newProgress);
            result.put("keywords", getUserKeywords(userID));
            result.put("message", "故事重新开始！");

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("重新开始故事失败", e);
            return ResponseEntity.badRequest()
                    .body(Map.of("error", "重新开始失败，请重试"));
        }
    }

    /**
     * 获取用户的所有故事模板列表
     */
    @GetMapping("/user-stories")
    public ResponseEntity<Map<String, Object>> getUserStories(@RequestParam String userID) {
        log.info("获取用户故事列表: 用户ID={}", userID);

        try {
            // 1. 获取所有故事模板
            List<StoryTemplate> allTemplates = storyTemplateMapper.selectList(null);

            if (allTemplates == null || allTemplates.isEmpty()) {
                return ResponseEntity.ok(Map.of("stories", new ArrayList<>()));
            }

            // 2. 为每个模板获取第一页内容
            List<Map<String, Object>> storyList = new ArrayList<>();

            for (StoryTemplate template : allTemplates) {
                // 获取第一页
                StoryPage firstPage = storyPageMapper.selectOne(
                        new LambdaQueryWrapper<StoryPage>()
                                .eq(StoryPage::getTemplateId, template.getId())
                                .isNull(StoryPage::getParentPageId)
                                .orderByAsc(StoryPage::getPageNumber)
                                .last("LIMIT 1"));

                Map<String, Object> storyInfo = new HashMap<>();
                storyInfo.put("id", template.getId());
                storyInfo.put("title", template.getTitle());
                storyInfo.put("description", template.getDescription());
                storyInfo.put("difficultyLevel", template.getDifficultyLevel());
                storyInfo.put("wordList", template.getWordList());
                storyInfo.put("totalPages", template.getTotalPages());
                storyInfo.put("theme", template.getTheme());
                storyInfo.put("createdAt", template.getCreatedAt());
                storyInfo.put("updatedAt", template.getUpdatedAt());

                if (firstPage != null) {
                    storyInfo.put("firstPageContent", cleanContent(firstPage.getEnglishContent()));
                } else {
                    storyInfo.put("firstPageContent", "暂无内容");
                }

                storyList.add(storyInfo);
            }

            // 按创建时间倒序排列
            storyList.sort((a, b) -> {
                LocalDateTime timeA = (LocalDateTime) a.get("createdAt");
                LocalDateTime timeB = (LocalDateTime) b.get("createdAt");
                return timeB.compareTo(timeA);
            });

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("stories", storyList);
            result.put("total", storyList.size());

            log.info("成功获取用户故事列表，共 {} 个故事", storyList.size());
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("获取用户故事列表失败", e);
            return ResponseEntity.badRequest()
                    .body(Map.of("error", "获取故事列表失败: " + e.getMessage()));
        }
    }

    /**
     * 加载指定模板的故事
     */
    @PostMapping("/load-specific")
    public ResponseEntity<Map<String, Object>> loadSpecificStory(
            @RequestParam String userID,
            @RequestParam Long templateId) {

        log.info("加载指定故事: 用户={}, 模板={}", userID, templateId);

        try {
            // 1. 验证模板是否存在
            StoryTemplate template = storyTemplateMapper.selectById(templateId);
            if (template == null) {
                return ResponseEntity.badRequest()
                        .body(Map.of("error", "指定的故事不存在"));
            }

            // 2. 强制为指定模板创建新进度（不复用已有进度）
            UserStoryProgress progress = createNewProgressForTemplate(userID, templateId);

            // 3. 获取当前页面（应该是第一页）
            StoryPage currentPage = getCurrentPage(progress);
            if (currentPage == null) {
                return ResponseEntity.badRequest()
                        .body(Map.of("error", "故事页面数据异常"));
            }

            // 4. 重建页面历史（对于新进度，只有第一页）
            List<StoryPage> pageHistory = rebuildPageHistory(progress, templateId);

            // 5. 获取用户关键词
            List<String> wordList = getUserKeywords(userID);

            // 6. 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("template", template);
            result.put("currentPage", currentPage);
            result.put("pageHistory", pageHistory);
            result.put("currentPageIndex", pageHistory.size() - 1);
            result.put("progress", progress);
            result.put("keywords", wordList);

            log.info("成功加载指定故事: {}", template.getTitle());
            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("加载指定故事失败", e);
            return ResponseEntity.badRequest()
                    .body(Map.of("error", "加载故事失败: " + e.getMessage()));
        }
    }

    /**
     * 为指定模板创建新的进度记录
     */
    private UserStoryProgress createNewProgressForTemplate(String userId, Long templateId) {
        log.info("为模板 {} 创建新的进度记录", templateId);

        try {
            // 标记该用户对此模板的所有未完成进度为完成
            List<UserStoryProgress> existingProgresses = userStoryProgressMapper.selectList(
                    new LambdaQueryWrapper<UserStoryProgress>()
                            .eq(UserStoryProgress::getUserId, userId)
                            .eq(UserStoryProgress::getTemplateId, templateId)
                            .eq(UserStoryProgress::getIsCompleted, false));

            for (UserStoryProgress existingProgress : existingProgresses) {
                existingProgress.setIsCompleted(true);
                existingProgress.setCompletedAt(LocalDateTime.now());
                userStoryProgressMapper.updateById(existingProgress);
                log.info("标记旧进度 {} 为完成", existingProgress.getId());
            }

            // 获取第一页
            StoryPage firstPage = storyPageMapper.selectOne(
                    new LambdaQueryWrapper<StoryPage>()
                            .eq(StoryPage::getTemplateId, templateId)
                            .isNull(StoryPage::getParentPageId)
                            .orderByAsc(StoryPage::getPageNumber)
                            .last("LIMIT 1"));

            if (firstPage == null) {
                throw new RuntimeException("模板 " + templateId + " 没有找到第一页");
            }

            // 创建新的进度记录
            UserStoryProgress newProgress = new UserStoryProgress();
            newProgress.setUserId(userId);
            newProgress.setTemplateId(templateId);
            newProgress.setCurrentPageId(firstPage.getId());
            newProgress.setChoicesMade(new ArrayList<>());
            newProgress.setIsCompleted(false);
            newProgress.setStartedAt(LocalDateTime.now());
            newProgress.setUpdatedAt(LocalDateTime.now());

            // 保存到数据库
            userStoryProgressMapper.insert(newProgress);
            log.info("为模板 {} 创建新进度记录成功，ID={}", templateId, newProgress.getId());

            return newProgress;

        } catch (Exception e) {
            log.error("为模板 {} 创建新进度记录失败", templateId, e);
            throw new RuntimeException("创建新进度记录失败", e);
        }
    }

    /**
     * 删除故事
     */
    @DeleteMapping("/delete")
    public ResponseEntity<Map<String, Object>> deleteStory(
            @RequestParam String userID,
            @RequestParam Long templateId) {

        log.info("删除故事: 用户={}, 模板={}", userID, templateId);

        try {
            // 1. 验证模板是否存在
            StoryTemplate template = storyTemplateMapper.selectById(templateId);
            if (template == null) {
                return ResponseEntity.badRequest()
                        .body(Map.of("error", "指定的故事不存在"));
            }

            // 2. 删除用户进度记录
            userStoryProgressMapper.delete(
                    new LambdaQueryWrapper<UserStoryProgress>()
                            .eq(UserStoryProgress::getUserId, userID)
                            .eq(UserStoryProgress::getTemplateId, templateId));

            // 3. 删除故事页面（级联删除会自动处理）
            storyPageMapper.delete(
                    new LambdaQueryWrapper<StoryPage>()
                            .eq(StoryPage::getTemplateId, templateId));

            // 4. 删除故事模板
            storyTemplateMapper.deleteById(templateId);

            log.info("成功删除故事: {}", template.getTitle());
            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "message", "故事删除成功"));

        } catch (Exception e) {
            log.error("删除故事失败", e);
            return ResponseEntity.badRequest()
                    .body(Map.of("error", "删除故事失败: " + e.getMessage()));
        }
    }
}